<template>
  <!-- 需要配置图片上传地址 否则上传图片不可用 -->
  <div class="editor" style="border: 1px solid #ccc;">
    <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
        :mode="mode"
    />
    <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model="html"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="onCreated"
    />
  </div>
</template>

<script>
  import '@wangeditor/editor/dist/css/style.css'
  // import { DomEditor } from '@wangeditor/editor'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

  export default {
    name: 'ArticleEditor',
    components: { Editor, Toolbar },
    props: {
      content: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        // 富文本编辑器
        editor: null,
        html: '',
        toolbarConfig: { 
          excludeKeys: [ 'headerSelect', 'fullScreen', 'codeBlock', 'todo', 'insertTable' ]
        },
        // editorConfig: { placeholder: '请输入内容...', maxLength: 1000 },
        editorConfig: {
          placeholder: "请输入内容...",
          autoFocus: false,   // 是否自动聚焦

          // 所有的菜单配置，都要在 MENU_CONF 属性下
          MENU_CONF: {
            uploadImage: {
              server: 'http://127.0.0.1:5268/api/image/uploadImg',
              fieldName: 'article-image'
            },
            insertImage: {
              // 插入图片之后的回调
              onInsertedImage(imageNode) {
                if (imageNode == null) return

                const { src, alt, url, href } = imageNode
                console.log('inserted image', src, alt, url, href)
                let filename = src.split('/')
                filename = filename[filename.length - 1]
                console.log(filename)
              }
              // checkImage: customCheckImageFn, // 也支持 async 函数
              // parseImageSrc: customParseImageSrc, // 也支持 async 函数
            }
          },
        },
        // 编辑器模式
        mode: 'simple', // or 'simple'
      }
    },
    watch: {
      content(newVal) {
        if (newVal.indexOf('<p>') === -1) newVal = `<p>${newVal}</p>`
        this.html = newVal
      }
    },
    methods: {
      // 富文本编辑器 在此处执行输出配置等
      onCreated(editor) {
        this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      },
    },
    mounted() {
      // 模拟 ajax 请求，异步渲染编辑器
      // setTimeout(() => {
      //     this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
      // }, 1500)
    },
    beforeDestroy() {
      const editor = this.editor
      // const toolbar = DomEditor.getToolbar(editor)
      // console.log(toolbar)
      if (editor == null) return
      editor.destroy() // 组件销毁时，及时销毁编辑器
    },
  }
</script>

<style scoped>
  .editor {
    margin-left: 30px;
    margin-bottom: 20px;
  }
</style>